// pages/myPhone/myPhone.js
import RegisterApi from "../../api/register";
import MyInfoApi from '../../api/myInfo'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    code:'',
    codeFlag:false,
    time: 60 * 1000,
    password:'',
    userId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userId:options.userId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  handlerGobackClick(){
    wx.navigateBack()
  },
  /**
   * 保存
   */
  async enter(){
    const phone = this.data.phone
    const password = this.data.password
    const code = this.data.code
    if(password == ''){
      wx.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(phone == ''){
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(code == ''){
      wx.showToast({
        title: '请输入验证码',
        icon: 'none',
        duration: 2000
      })
      return
    }
    const param = {
      "id": this.data.userId,
      "telNum": phone,
      "verifyCode": code,
      "password":this.data.password
    }
    const res = await MyInfoApi.changeTelNum(param)
    if(res.code == 100){
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }else {
      wx.navigateBack()
    }
  },
  /**
   * 发送验证码
   */
  async sendCode(){
    if (this.data.codeFlag){
      return
    }
    const phone = this.data.phone
    if(phone == ''){
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    //验证手机号是否正确
    if(!(/^1[34578]\d{9}$/.test(phone))){
      wx.showToast({
        title: '请输入正确手机号',
        icon: 'none',
        duration: 2000
      })
      return
    }
    //查询用户是否存在
    const param = {
      telNum:phone
    }
    let res = await  RegisterApi.sendCode(param)
    if(res.code == 100){
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }else{
      //如果存在，开始倒计时
      this.setData({
        codeFlag:true
      })
      this.start()
    }
  },
  start() {
    const countDown = this.selectComponent('.control-count-down');
    countDown.start();
  },
  finished() {
    this.setData({
      codeFlag:false
    })
  },
  /**
   * input 数据绑定
   */
  updateValue(e) {
    let name = e.currentTarget.dataset.name;
    let nameMap = {}
    nameMap[name] = e.detail
    this.setData(nameMap)
  },
})
